//
//  DateSelectViewController.m
//  QRMaster
//
//  Created by myApple on 15/7/22.
//  Copyright (c) 2015年 myApple. All rights reserved.
//

#import "DateSelectViewController.h"
#import "PromptInfoView.h"
#import "RequestNetWork.h"
#import "guestTimeModel.h"
#import "Reachability.h"
#import "AppDelegate.h"
#import "IQKeyboardManager.h"

@interface DateSelectViewController ()<UITextFieldDelegate,UIAlertViewDelegate>
{
    UIDatePicker * selectPickView;
    UITextField * beginTextField;
    UITextField * endTextField;
    
    NSString * dateString;
    NSString * timeString;
    
    UIButton * dateBtn;
    UIButton * timeBtn;
    
    NSMutableArray * postArray;//上传信息参数
    
    AppDelegate * appDelegate;
    UIButton * backBtn;
    
    UIActivityIndicatorView *  _activityIndicator;
    
    //多语言
    UILabel * titleLabel;
    UIButton * postBtn;
    UILabel * beginDateTimeLabel;
    UIButton * makeSureBtn;
    UILabel * endDateTimeLabel;
}

@end

@implementation DateSelectViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    postArray = [[NSMutableArray alloc]init];
    // Do any additional setup after loading the view.
    appDelegate = [UIApplication sharedApplication].delegate;
    [self prepareBckView];
    [self prepareTitleView];
    [self prepareDateTimePickView];
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    postBtn.hidden = NO;
    backBtn.hidden = NO;
    [IQKeyboardManager sharedManager].enableAutoToolbar = NO;
    
}

-(void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    self.navigationItem.title = NSLocalizedString(@"setTime", nil);
    [postBtn setTitle:NSLocalizedString(@"takePost", nil) forState:0];
    beginDateTimeLabel.text = NSLocalizedString(@"beginTime", nil);
    beginTextField.placeholder =  NSLocalizedString(@"chooseBeginTime", nil);
    endDateTimeLabel.text =  NSLocalizedString(@"endTime", nil);
    endTextField.placeholder = NSLocalizedString(@"chooseEndTime", nil);
}

-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    postBtn.hidden = YES;
     backBtn.hidden = YES;
}
-(void)setBeginTime:(NSString *)beginTime
{
    _beginTime = beginTime;
    if (beginTime.length >= 16) {
        _beginTime = [beginTime substringToIndex:16];
    }
    
}

-(void)setEndTime:(NSString *)endTime
{
    _endTime = endTime;
    if (endTime.length >= 16) {
        _endTime = [endTime substringToIndex:16];
    }
    
}

-(void)prepareBckView
{
    backBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    backBtn.frame = CGRectMake(0, 0, 56, 40);
    [backBtn addTarget:self action:@selector(shouldSave) forControlEvents:UIControlEventTouchUpInside];
    [self.navigationController.navigationBar addSubview:backBtn];
}

#pragma mark -------回退键 是否保存
-(void)shouldSave
{
    if (beginTextField.text.length != 0 && endTextField.text.length != 0) {
        UIAlertView * alertView = [[UIAlertView alloc]initWithTitle:nil message:NSLocalizedString(@"shouldSave", @"保存本次编辑?") delegate:self cancelButtonTitle:NSLocalizedString( @"notSave", nil) otherButtonTitles:NSLocalizedString(@"save", nil), nil];
        [alertView show];
    }
    else
    {
        [self BackClick];
    }
}

-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 1) {
        [self saveTime];
    }
    else
    {
        [self BackClick];
    }
}

-(void)prepareTitleView
{
    float ScreenWidth = [UIScreen mainScreen].bounds.size.width;
    float x = ScreenWidth - 60;
    float y = 2;
    float width = 60;
    float height = 40;

    postBtn =[UIButton buttonWithType:UIButtonTypeCustom];
    postBtn.frame = CGRectMake(x, y, width, height);
    [postBtn setTitle:NSLocalizedString(@"takePost", nil) forState:0];
    [postBtn setTitleColor:[UIColor whiteColor] forState:0];
    postBtn.titleLabel.font = [UIFont systemFontOfSize:14.0];
    [postBtn addTarget:self action:@selector(saveTime) forControlEvents:UIControlEventTouchUpInside];
    [self.navigationController.navigationBar addSubview:postBtn];
    
    //起始时间
    x = 10;
    y = 30;
    height = 20;
    width = 80;
    beginDateTimeLabel =[[UILabel alloc]initWithFrame:CGRectMake(x, y, width, height)];
    beginDateTimeLabel.text = NSLocalizedString(@"beginTime", nil);
    beginDateTimeLabel.font = [UIFont systemFontOfSize:14.0];
    [self.view addSubview:beginDateTimeLabel];
    
    x += width;
    width = ScreenWidth - x - 10;
    y -= 10;
    height = 40;
    beginTextField =[[UITextField alloc]initWithFrame:CGRectMake(x, y, width, height)];
    beginTextField.borderStyle = UITextBorderStyleRoundedRect;
    beginTextField.placeholder =  NSLocalizedString(@"chooseBeginTime", nil);
    beginTextField.delegate = self;
    beginTextField.inputView = [[UIView alloc]init];//不弹起键盘
    [beginTextField becomeFirstResponder];
    beginTextField.text = _beginTime;
    [self.view addSubview:beginTextField];
    
    //结束时间
    x = 10;
    y += height + 15;
    height = 20;
    width = 80;
    endDateTimeLabel =[[UILabel alloc]initWithFrame:CGRectMake(x, y, width, height)];
    endDateTimeLabel.text =  NSLocalizedString(@"endTime", nil);
    endDateTimeLabel.font = [UIFont systemFontOfSize:14.0];
    [self.view addSubview:endDateTimeLabel];
    
    x += width;
    width = ScreenWidth - x - 10;
    y -= 10;
    height = 40;
    endTextField =[[UITextField alloc]initWithFrame:CGRectMake(x, y, width, height)];
    endTextField.borderStyle = UITextBorderStyleRoundedRect;
    endTextField.placeholder = NSLocalizedString(@"chooseEndTime", nil);
    endTextField.delegate = self;
    endTextField.inputView = [[UIView alloc]init];
    endTextField.text = _endTime;
    [self.view addSubview:endTextField];

}

-(void)saveTime
{
    [postArray removeAllObjects];
    if (beginTextField.text == nil || beginTextField.text.length == 0) {
        [PromptInfoView showMessage:NSLocalizedString(@"beginTimeNil", nil) superView:self.view];
        return;
    }
    if (endTextField.text == nil || endTextField.text.length == 0) {
        [PromptInfoView showMessage:NSLocalizedString(@"endTimeNil", nil) superView:self.view];
        return;
    }
    if ([self IsHaveNetwork]) {
        return;
    }
    for (int i = 0; i < _selectRoom.count; i ++) {
       guestTimeModel * model = _roomInfo[[_selectRoom[i]integerValue]];
        NSMutableDictionary * postRoomDict = [[NSMutableDictionary alloc]init];
        [postRoomDict setValue:model.buildId forKey:@"buildId"];
        [postRoomDict setValue:model.floorId forKey:@"floorId"];
        [postRoomDict setValue:model.roomId forKey:@"roomId"];
        [postRoomDict setValue:beginTextField.text forKey:@"startTime"];
        [postRoomDict setValue:endTextField.text forKey:@"endTime"];
        [postArray addObject:postRoomDict];
    }
    NSString * json = nil;
    if ([NSJSONSerialization isValidJSONObject:postArray]) {
        NSError *error;
        NSData * jsonData = [NSJSONSerialization dataWithJSONObject:postArray options:NSJSONWritingPrettyPrinted error:&error];
        json = [[NSString alloc]initWithData:jsonData encoding:NSUTF8StringEncoding];
    }

    [self startWaiting:nil color:nil addToView:self.view];
    NSUserDefaults * userInfo = [NSUserDefaults standardUserDefaults];
    NSMutableDictionary * postDict = [[NSMutableDictionary alloc]init];
    [postDict setValue:[userInfo objectForKey:@"uid"] forKey:@"id"];
    [postDict setValue:[userInfo objectForKey:@"token"] forKey:@"token"];
    [postDict setValue:_communityId forKey:@"communityId"];
    [postDict setValue:_guestId forKey:@"userId"];
     RequestNetWork * rnw = [[RequestNetWork alloc]init];
    NSString *urlStr = @"";
    if (_groupId) {
        //给组管理员分配时间
        [postDict setValue:endTextField.text forKey:@"groupEndTime"];
        [postDict setValue:beginTextField.text forKey:@"groupStartTime"];
        [postDict setValue:_groupId forKey:@"groupId"];
        urlStr = POST(EDITGROUPTIME);
    }
    else
    {
        [postDict setValue:json forKey:@"json"];
        urlStr = POST(SETCLIENTROOMTIME);
    }
    
    [rnw initWithPath:urlStr params:postDict block:^(id downLoadData, id error)
     {
         [self stopWaiting];
         if ([downLoadData objectForKey:@"data"]) {
            [PromptInfoView showMessage:[downLoadData objectForKey:@"info"]];
             if (_groupId) {
                 [QRSingleton sharedQRSingleton].groupBeginTime = beginTextField.text;
                 [QRSingleton sharedQRSingleton].groupEndTime = endTextField.text;
                 [self BackClick];
                 return ;
             }
             if (_getTime) {
                 _getTime(beginTextField.text,endTextField.text);
             }
             [self BackClick];
         }
         else
         {
             if ([[error objectForKey:@"status"]integerValue] == 505) {
                 NSDictionary * timeData = [error objectForKey:@"data"];
                 [PromptInfoView showMessage:[NSString stringWithFormat:@"%@(%@~%@)",NSLocalizedString(@"activeTime", nil),[timeData objectForKey:@"starttime"],[timeData objectForKey:@"endtime"]] superView:self.view];
             }
             else
             {
                 [PromptInfoView showMessage:[error objectForKey:@"info"] superView:self.view];
             }
         }
     }
     ];

}

#pragma mark -- 准备时间试图
-(void)prepareDateTimePickView
{
    float ScreenWidth = [UIScreen mainScreen].bounds.size.width;
    float ScreenHeight = [UIScreen mainScreen].bounds.size.height;
    float x = 10;
    float y = ScreenHeight - 342;
    float width = ScreenWidth - 2 * 10;
    float height = 276 ;
    
    UIView * backView = [[UIView alloc]initWithFrame:CGRectMake(x, y, width, height)];
    backView.backgroundColor = [UIColor clearColor];
    backView.layer.borderColor = RGBA(125, 194, 52, 1).CGColor;
    backView.layer.borderWidth = 1.0;
    backView.layer.cornerRadius = 5;
    backView.layer.masksToBounds = YES;
    [self.view addSubview:backView];
    
    x = 0;
    y = 0;
    width = backView.frame.size.width / 2.0;
    height = 30;
    dateBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    dateBtn.frame = CGRectMake(x, y, width, height);
    [dateBtn setTitleColor:[UIColor blackColor] forState:0];
    [dateBtn setBackgroundColor:[UIColor colorWithRed:125/255.0 green:194/255.0 blue:52/255.0 alpha:0.18]];
    [dateBtn addTarget:self action:@selector(selectDate:) forControlEvents:UIControlEventTouchUpInside];
    [backView addSubview:dateBtn];
    
    UIView * dateLineView = [[UIView alloc]initWithFrame:CGRectMake(width, y, 1, height)];
    dateLineView.backgroundColor = RGBA(125, 194, 52, 1);
    [backView addSubview:dateLineView];
    
    x += width - 1;
    timeBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    timeBtn.frame = CGRectMake(x, y, width, height);
    [timeBtn setTitleColor:[UIColor blackColor] forState:0];
    [timeBtn addTarget:self action:@selector(selectTime:) forControlEvents:UIControlEventTouchUpInside];
    [backView addSubview:timeBtn];
    
    UIView * timeLineView = [[UIView alloc]initWithFrame:CGRectMake(0, height, backView.frame.size.width, 1)];
    timeLineView.backgroundColor = RGBA(125, 194, 52, 1);
    [backView addSubview:timeLineView];
    
     x = 0;
    y += height;
    width = backView.frame.size.width;
    height = 216;
    selectPickView = [[UIDatePicker alloc]initWithFrame:CGRectMake(x, y, width, height)];
    selectPickView.datePickerMode = UIDatePickerModeDate;
    [selectPickView addTarget:self action:@selector(selectDateTime:) forControlEvents:UIControlEventValueChanged];
    [backView addSubview:selectPickView];

    NSDate *date = [NSDate dateWithTimeIntervalSinceNow:0.0];
    // 打印日期：中间的空格可以用'at'或'T'等字符来分隔
    NSDateFormatter *dateFomatter = [[NSDateFormatter alloc] init];
    [dateFomatter setDateFormat:@"yyyy-MM-dd"];
    [dateFomatter setLocale:[[NSLocale alloc]initWithLocaleIdentifier:@"ch_CN"]];
    [dateFomatter stringFromDate:date];
    dateString = [dateFomatter stringFromDate:date];
    [dateBtn setTitle:dateString forState:0];
    selectPickView.minimumDate = date;

    
    [dateFomatter setDateFormat:@"HH:mm"];
    timeString = [dateFomatter stringFromDate:date];
    [timeBtn setTitle:timeString forState:0];
    
    x = 0;
    width = backView.frame.size.width;
    y += height - 10;
    height = 40;
    makeSureBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    makeSureBtn.frame = CGRectMake(x, y, width, height);
    [makeSureBtn setTitle:NSLocalizedString(@"alterSure", nil) forState:0];
    [makeSureBtn setTitleColor:RGBA(135, 199, 66, 1) forState:0];
    makeSureBtn.layer.cornerRadius = 5;
    makeSureBtn.layer.masksToBounds = YES;
    makeSureBtn.layer.borderWidth = 1.0;
    makeSureBtn.layer.borderColor = RGBA(135, 199, 66, 1).CGColor;
    [makeSureBtn addTarget:self action:@selector(makeSure:) forControlEvents:UIControlEventTouchUpInside];
    [backView addSubview:makeSureBtn];
}

//改变滚动条的值
-(void)selectDateTime:(UIDatePicker *)pickView
{
    NSDateFormatter * df = [NSDateFormatter new];
    [df setDateFormat:@"yyyy-MM-dd"];
    [df setLocale:[[NSLocale alloc]initWithLocaleIdentifier:@"ch_CN"]];
    if (pickView.datePickerMode == UIDatePickerModeDate) {
        dateString = [df stringFromDate:pickView.date];
        [dateBtn setTitle:dateString forState:0];
    }
    else
    {
        [df setDateFormat:@"HH:mm"];
        timeString = [df stringFromDate:pickView.date];
        [timeBtn setTitle:timeString forState:0];
    }
}

//选择日期
-(void)selectDate:(UIButton *)btn
{
    [timeBtn setBackgroundColor:[UIColor clearColor]];
    [dateBtn setBackgroundColor:[UIColor colorWithRed:125/255.0 green:194/255.0 blue:52/255.0 alpha:0.18]];
    selectPickView.datePickerMode = UIDatePickerModeDate;
    if ([endTextField isEditing]) {
        selectPickView.datePickerMode = UIDatePickerModeDate;
        NSDateFormatter * df = [NSDateFormatter new];
        [df setDateFormat:@"yyyy-MM-dd"];
        [df setLocale:[[NSLocale alloc]initWithLocaleIdentifier:@"ch_CN"]];
        selectPickView.minimumDate = [df dateFromString:dateString];
        [timeBtn setTitle:timeString forState:0];
    }
    else
    {
        NSDate *date = [NSDate dateWithTimeIntervalSinceNow:0.0];
        // 打印日期：中间的空格可以用'at'或'T'等字符来分隔
        NSDateFormatter *dateFomatter = [[NSDateFormatter alloc] init];
        [dateFomatter setDateFormat:@"yyyy-MM-dd"];
        [dateFomatter setLocale:[[NSLocale alloc]initWithLocaleIdentifier:@"ch_CN"]];
        [dateFomatter stringFromDate:date];
        selectPickView.minimumDate = date;
        [timeBtn setTitle:timeString forState:0];
    }
    
    
}

//选择时间
-(void)selectTime:(UIButton *)btn
{
    [dateBtn setBackgroundColor:[UIColor clearColor]];
    [timeBtn setBackgroundColor:[UIColor colorWithRed:125/255.0 green:194/255.0 blue:52/255.0 alpha:0.18]];
    selectPickView.datePickerMode = UIDatePickerModeCountDownTimer;
    if ([endTextField isEditing]) {
        NSDateFormatter *dateFomatter = [[NSDateFormatter alloc] init];
        [dateFomatter setDateFormat:@"HH:mm"];
        [dateFomatter setLocale:[[NSLocale alloc]initWithLocaleIdentifier:@"ch_CN"]];
        selectPickView.minimumDate =[dateFomatter dateFromString:timeString];
    }
    [dateBtn setTitle:dateString forState:0];
}

//确定按钮
-(void)makeSure:(UIButton *)btn
{
    if (beginTextField.editing) {
        NSDate *date = [NSDate dateWithTimeIntervalSinceNow:0.0];
        // 打印日期：中间的空格可以用'at'或'T'等字符来分隔
        NSDateFormatter *dateFomatter = [[NSDateFormatter alloc] init];
        [dateFomatter setDateFormat:@"yyyy-MM-dd HH:mm"];
        [dateFomatter setLocale:[[NSLocale alloc]initWithLocaleIdentifier:@"ch_CN"]];
        [dateFomatter stringFromDate:date];
        NSComparisonResult result = [[dateFomatter dateFromString:[NSString stringWithFormat:@"%@ %@:59",dateString,timeString]] compare:date];
        if (result == NSOrderedDescending || result == NSOrderedSame) {
            beginTextField.text = [NSString stringWithFormat:@"%@ %@",dateString,timeString];
            [endTextField becomeFirstResponder];
        }
        else
        {
            [PromptInfoView showMessage:NSLocalizedString(@"beginTimeError", nil) superView:self.view];
        }
    }
    else
    {
        NSDateFormatter *dateFomatter = [[NSDateFormatter alloc] init];
        [dateFomatter setDateFormat:@"yyyy-MM-dd HH:mm"];
        [dateFomatter setLocale:[[NSLocale alloc]initWithLocaleIdentifier:@"ch_CN"]];
        NSComparisonResult result = [[dateFomatter dateFromString:beginTextField.text] compare:[dateFomatter dateFromString:[NSString stringWithFormat:@"%@ %@",dateString,timeString]]];
        if (result == NSOrderedAscending) {
             endTextField.text = [NSString stringWithFormat:@"%@ %@",dateString,timeString];
        }
        else
        {
            [PromptInfoView showMessage:NSLocalizedString(@"timeErrorChoose", nil) superView:self.view];
        }
       
    }
    
}

-(void)textFieldDidBeginEditing:(UITextField *)textField
{
    selectPickView.datePickerMode = UIDatePickerModeDate;
    [timeBtn setBackgroundColor:[UIColor clearColor]];
    [dateBtn setBackgroundColor:[UIColor colorWithRed:125/255.0 green:194/255.0 blue:52/255.0 alpha:0.18]];
}

//初始化风火轮
-(void)prepareActivityIndicator
{
    _activityIndicator = [[UIActivityIndicatorView alloc]initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
    _activityIndicator.frame = CGRectMake(self.view.frame.size.width / 2.0 -15, self.view.frame.size.height / 2.0 - 15, 30, 30);
    _activityIndicator.hidden = NO;
    [self.view addSubview:_activityIndicator];
}

//判断是否有网络
-(BOOL)IsHaveNetwork
{
    Reachability * reach = [Reachability reachabilityForInternetConnection];
    if([reach currentReachabilityStatus] == NotReachable) {
        [PromptInfoView showMessage:NSLocalizedString(@"noNetWork", nil)];
        return YES;
    }
    return NO;
}


-(void)BackClick
{
    [self.view endEditing:YES];
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
